import React, { useState, useRef, useEffect } from 'react';
import { Select as AntdSelect, SelectProps, Input, Button } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';

interface EditableSelectProps extends Omit<SelectProps, 'options'> {
  className?: string;
  options: { label: string; value: string }[];
  onOptionsChange?: (newOptions: { label: string; value: string }[]) => void;
  allowAdd?: boolean;
  allowDelete?: boolean;
  addButtonText?: string;
  placeholder?: string;
}

export const EditableSelect: React.FC<EditableSelectProps> = ({
  className,
  options = [],
  onOptionsChange,
  allowAdd = true,
  allowDelete = true,
  addButtonText = '添加选项',
  placeholder = '请选择或添加选项',
  ...props
}) => {
  const [isAdding, setIsAdding] = useState(false);
  const [newOptionValue, setNewOptionValue] = useState('');
  const [newOptionLabel, setNewOptionLabel] = useState('');
  const [hoveredOption, setHoveredOption] = useState<string | null>(null);
  const inputRef = useRef<any>(null);

  useEffect(() => {
    if (isAdding && inputRef.current) {
      inputRef.current.focus();
    }
  }, [isAdding]);

  const handleAddOption = () => {
    if (newOptionValue.trim() && newOptionLabel.trim()) {
      const newOption = {
        label: newOptionLabel.trim(),
        value: newOptionValue.trim(),
      };

      // 检查是否已存在相同的值
      const exists = options.some((option) => option.value === newOption.value);
      if (!exists) {
        const newOptions = [...options, newOption];
        onOptionsChange?.(newOptions);
        setNewOptionValue('');
        setNewOptionLabel('');
        setIsAdding(false);
      }
    }
  };

  const handleDeleteOption = (valueToDelete: string) => {
    const newOptions = options.filter((option) => option.value !== valueToDelete);
    onOptionsChange?.(newOptions);
    setHoveredOption(null);
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleAddOption();
    } else if (e.key === 'Escape') {
      setIsAdding(false);
      setNewOptionValue('');
      setNewOptionLabel('');
    }
  };

  const customOptions = options.map((option) => ({
    ...option,
    label: (
      <div
        className="group flex w-full items-center justify-between"
        onMouseEnter={() => setHoveredOption(option.value)}
        onMouseLeave={() => setHoveredOption(null)}
      >
        <span>{option.label}</span>
        {allowDelete && hoveredOption === option.value && (
          <Button
            type="text"
            size="small"
            icon={<DeleteOutlined />}
            onClick={(e) => {
              e.stopPropagation();
              handleDeleteOption(option.value);
            }}
            className="text-red-500 hover:text-red-700 hover:bg-red-50 opacity-0 transition-opacity duration-200 group-hover:opacity-100"
            title="删除选项"
          />
        )}
      </div>
    ),
  }));

  const dropdownRender = (menu: React.ReactNode) => (
    <div>
      {menu}
      {allowAdd && (
        <div className="border-t border-gray-200 p-2">
          {isAdding ? (
            <div className="space-y-2">
              <Input
                ref={inputRef}
                size="small"
                placeholder="选项值"
                value={newOptionValue}
                onChange={(e) => setNewOptionValue(e.target.value)}
                onKeyDown={handleKeyPress}
              />
              <Input
                size="small"
                placeholder="选项标签"
                value={newOptionLabel}
                onChange={(e) => setNewOptionLabel(e.target.value)}
                onKeyDown={handleKeyPress}
              />
              <div className="flex gap-1">
                <Button
                  size="small"
                  type="primary"
                  onClick={handleAddOption}
                  disabled={!newOptionValue.trim() || !newOptionLabel.trim()}
                >
                  添加
                </Button>
                <Button
                  size="small"
                  onClick={() => {
                    setIsAdding(false);
                    setNewOptionValue('');
                    setNewOptionLabel('');
                  }}
                >
                  取消
                </Button>
              </div>
            </div>
          ) : (
            <Button
              type="text"
              size="small"
              icon={<PlusOutlined />}
              onClick={() => setIsAdding(true)}
              className="w-full text-left"
            >
              {addButtonText}
            </Button>
          )}
        </div>
      )}
    </div>
  );

  return (
    <AntdSelect
      className={className}
      options={customOptions}
      placeholder={placeholder}
      dropdownRender={dropdownRender}
      {...props}
    />
  );
};
